//
//  StatusPictureView.swift
//  weibo19
//
//  Created by Arvin on 15/11/15.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit
import SDWebImage

private let statusPictuerCell = "statusPictureCell"
let pictuerMargin = 5
class StatusPictureView: UICollectionView {
    
    var pic_URLs: [NSURL]? {
        didSet {
           reloadData()
            
            let pictureViewSize = calcuPictureViewSize()
            // picture的约束
            // 注意: 这里直接设置.Size.equalTo无效
            // 用update设置约束
            self.snp_updateConstraints { (make) -> Void in
                make.width.equalTo(pictureViewSize.width)
                make.height.equalTo(pictureViewSize.height)
            }
        }
    }
    
    private func calcuPictureViewSize() -> CGSize {
        let pictureWidth = screenWidth - CGFloat(2 * StatusCellMargin)
        // 如果在ip6上显示正常, 而在6plus上显示不正常, 则将下面的除数小数后跟个1
        let itemWidth = (pictureWidth - CGFloat(2 * pictuerMargin)) / 3.0000001
        
        let layout = collectionViewLayout as? UICollectionViewFlowLayout
        layout?.itemSize = CGSizeMake(itemWidth, itemWidth)
        guard let count = pic_URLs?.count else {
            return CGSizeZero
        }
        
        if count == 0 {
            return CGSizeZero
        }
        
        // test.text = "\(pic_URLs?.count ?? 0)"
        
        if count == 1 {
            let URL = pic_URLs?.first
            // 从本地磁盘中取图片
            let image = SDImageCache().imageFromDiskCacheForKey(URL?.absoluteString)
            guard let size = image?.size else {
                return CGSizeMake(180, 140)
            }
            layout?.itemSize  = size
            return size
        }
        
        if count == 4 {
            let pw = itemWidth * 2 + CGFloat(pictuerMargin)
            return CGSizeMake(pw, pw)
        }
        
        // 这里计算行数
        // 1,2,3 -> 1
        // 4,5,6 -> 2
        // 7,8,9 -> 3
        let row = CGFloat((count + 2) / 3)
        
        let h = row * itemWidth + (row - 1) * CGFloat(pictuerMargin)
        return CGSizeMake(pictureWidth, h)
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = CGFloat(pictuerMargin)
        layout.minimumLineSpacing = CGFloat(pictuerMargin)
        super.init(frame: frame, collectionViewLayout: layout)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = UIColor.whiteColor()
        self.dataSource = self
        registerClass(StatusPictuerCell.self, forCellWithReuseIdentifier: statusPictuerCell)
    
        // 调试label
        // self.addSubview(test)

        // test.snp_makeConstraints { (make) -> Void in
           // make.centerX.equalTo(self.snp_centerX)
            // make.centerY.equalTo(self.snp_centerY)
        // }
    }
    
//    private lazy var test: UILabel = {
//        let t = UILabel()
//        t.font = UIFont.systemFontOfSize(24)
//        t.textColor = UIColor.redColor()
//        return t
//    }()
}

extension StatusPictureView: UICollectionViewDataSource {
    internal func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
         return self.pic_URLs?.count ?? 0
    }
    
    internal func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = dequeueReusableCellWithReuseIdentifier(statusPictuerCell, forIndexPath: indexPath) as! StatusPictuerCell
        cell.url = self.pic_URLs?[indexPath.item]
        return cell
    }
}

class StatusPictuerCell: UICollectionViewCell {
    
    var url: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(url)
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)

        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(iconView)
        // 等比例填充
        iconView.contentMode = .ScaleAspectFill
        // 裁剪
        iconView.clipsToBounds = true
        
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        contentView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(snp_edges)
        }
    }
    private lazy var iconView: UIImageView = UIImageView()
}